package controller

import (
	"myblogs/Lib"
	"myblogs/app/http/model/article"
	"myblogs/app/http/model/banner"
	"myblogs/app/http/model/category"
	"myblogs/app/http/model/tag"
	"myblogs/app/variable"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type IndexController struct {
	*BaseController
}

var (
	articleModel  *article.ArticleModel
	categoryModel *category.CategoryModel
	tagModel      *tag.TagModel
	bannerModel   *banner.BannerModel
)

func init() {
	articleModel = new(article.ArticleModel)
	categoryModel = new(category.CategoryModel)
	tagModel = new(tag.TagModel)
	bannerModel = new(banner.BannerModel)
}

func (i *IndexController) Index(c *gin.Context) {
	articles := articleModel.GetArticleList()
	for _, item := range articles {
		item.CreatedTimeStr = item.CreatedTime.Format("2006-01-02")

		cover := item.Cover
		if len(cover) == 0 {
			categoryInfo := categoryModel.GetCategoryInfo(item.CategoryId)
			item.Cover = categoryInfo.Cover
		}

		item.Cover = variable.ImgHost + item.Cover

		enId, _ := Lib.EnPwdCode([]byte(strconv.FormatInt(item.Id, 10)))
		item.ArticleId = enId
	}
	banners := bannerModel.GetBannerList()

	articleLatest := articleModel.GetArticleLatest()
	articleTotal := articleModel.GetArticleTotal()
	categoryTotal := categoryModel.GetCategoryTotal()
	tags := tagModel.GetTagAll(10)

	data := gin.H{
		"articles":      articles,
		"articleLatest": articleLatest,
		"articleTotal":  articleTotal,
		"categoryTotal": categoryTotal,
		"banners":       banners,
		"tags":          tags,
		"title":         "全栈工匠",
		"keywords":      "全栈开发，系统架构，后端博客，前端博客，后端框架，前端框架，PHP，Java，C#，Golang，Python，Vue，Html，Javascript，CSS",
		"description":   "一个专注于分享全栈以及系统架构技术和趋势的博客",
		"site":          "zhongxc.cc",
		"pvCount":       i.GetPv(),
		"likeCount":     articleModel.GetLikeCount(),
	}

	// 渲染模板
	c.HTML(http.StatusOK, "index.tmpl", data)
}
